// pages/home/home.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        currentCity:""
    },
    handleClick(){
        wx.navigateTo({
            url: '/pages/city/city'
        });
    },
    onShow(){
        var city = wx.getStorageSync("city");
        this.setData({
            currentCity:city
        })
    },
    onLoad(){
        /* 1、获取经纬度 */
        wx.getLocation({
            type: 'wgs84',
            altitude: false,
            success: (res)=>{
                console.log(res)
                var {latitude,longitude} =res;
                /* 2、根据经纬度获取当前所在的城市 */
                var key ="5SHBZ-N3D3I-M4IGS-5Y7DV-RQXEQ-SRBNV";
                var url =`https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=${key}&get_poi=1`
                wx.request({
                    url,
                    header: {'content-type':'application/json'},
                    method: 'GET',
                    dataType: 'json',
                    responseType: 'text',
                    success: (res)=>{
                        var currentCity = res.data.result.address_component.city;
                        var storageCity = wx.getStorageSync("city");
                        console.log(storageCity)
                        /* 3、当缓存中的城市和当前地理位置所在城市不一致的时候,弹窗 */
                        if(currentCity!=storageCity){
                            wx.showModal({
                                title: '切换城市',
                                content: '当时城市不是您所在的城市',
                                showCancel: true,
                                cancelText: '取消',
                                cancelColor: '#000000',
                                confirmText: '确定',
                                confirmColor: '#3CC51F',
                                success: (result) => {
                                    if(result.confirm){
                                        /* 确定设置为当前地理位置 */
                                        this.setData({
                                            currentCity
                                        })
                                        wx.setStorageSync("city", currentCity);
                                    }else{
                                        /* 取消就是缓存中的城市 */
                                        this.setData({
                                            currentCity:storageCity
                                        })
                                    }
                                }
                            });
                        }
                        
                    }
                });
            }
        });
    }
})